<template>
  <!-- 查询 -->
  <el-form :inline="true" :model="infor" class="demo-form-inline">
    <table>
      <tr>
        <td>
          <el-form-item label="姓名：">
            <el-input
              style="width: 200px"
              v-model="infor.employeeName"
              placeholder="请输入姓名"
              clearable
            />
          </el-form-item>
        </td>
        <td>
          <el-form-item label="部门：">
            <el-select
              style="width: 180px"
              v-model="infor.departmentId"
              placeholder="全部"
              clearable
              @change="bumen"
            >
              <el-option
                v-for="item in Department"
                :label="item.label"
                :value="item.value"
                :key="item.value"
              />
            </el-select>
          </el-form-item>
        </td>
        <td>
          <el-form-item label="职位:">
            <el-select
              style="width: 180px"
              v-model="infor.postsId"
              placeholder="全部"
              clearable
              @change="zhiwei"
            >
              <el-option
                v-for="item in Position"
                :label="item.label"
                :value="item.value"
                :key="item.value"
              />
            </el-select>
          </el-form-item>
        </td>
      </tr>
      <tr>
        <td>
          <el-form-item label="手机号:">
            <el-input
              style="width: 200px"
              v-model="infor.phone"
              placeholder="请输入手机号"
              clearable
            />
          </el-form-item>
        </td>
        <td>
          <el-form-item label="类别:">
            <el-select
              style="width: 180px"
              v-model="infor.employeeCategory"
              placeholder="全部"
              clearable
            >
              <el-option label="试用工" value="试用工" />
              <el-option label="实习生" value="实习生" />
              <el-option label="正式员工" value="正式员工" />
            </el-select>
          </el-form-item>
        </td>
        <td>
          <el-form-item>
            <el-button type="primary" @click="GetPersonnellist">查询</el-button>
            <el-button @click="resetForm">重置</el-button>
          </el-form-item>
        </td>
      </tr>
    </table>
  </el-form>
  <!-- 新增删除 -->
  <el-button type="primary" @click="JumptoNew">新增</el-button>
  <el-button type="primary" @click="DeletePersonnel">删除</el-button>
  <el-button type="primary" @click="exportExcel">导出Excel</el-button>
  <!-- 列表 -->
  <el-table
    :data="tableData"
    border
    style="width: 100%; margin-top: 20px"
    @selection-change="handleSelectionChange"
  >
    <el-table-column type="selection" width="55" />
    <el-table-column prop="employeeName" label="姓名" />
    <el-table-column prop="sex" label="性别">
      <template v-slot="scope">
        {{ scope.row.sex == false ? "男" : "女" }}
      </template>
    </el-table-column>
    <el-table-column prop="departmentId" label="部门" />
    <el-table-column prop="postsId" label="职位" />
    <el-table-column prop="phone" label="手机号" />
    <el-table-column prop="colleges" label="院校" />
    <el-table-column prop="specialized" label="专业" />
    <el-table-column prop="address" label="家庭住址" />
    <el-table-column prop="createDate" label="入职日期">
      <template v-slot="scope">
        {{ scope.row.createDate.substring(0, 10) }}
      </template>
    </el-table-column>
    <el-table-column label="工龄" width="center">
      <template v-slot="scoped">
        <span v-if="scoped.row.createName">{{
          calculateYearsDiff(scoped.row.createName)
        }}</span>
        <span v-else>0</span>
      </template>
    </el-table-column>
    <el-table-column prop="employeeCategory" label="类别"> </el-table-column>
    <el-table-column prop="state" label="状态">
      <template v-slot="scope">
        {{
          scope.row.state == 0
            ? "待入职"
            : scope.row.state == 1
            ? "试用期"
            : scope.row.state == 2
            ? "已转正"
            : "已离职"
        }}
      </template>
    </el-table-column>
    <el-table-column prop="createDate" label="创建日期">
      <template v-slot="scope">
        {{ scope.row.createDate.substring(0, 10) }}
      </template>
    </el-table-column>
    <el-table-column label="操作">
      <template v-slot="scope">
        <el-link type="primary" @click="chakan(scope.row.id)">修改</el-link>
        <el-link type="primary" @click="shanchu(scope.row.id)">删除</el-link>
      </template>
    </el-table-column>
  </el-table>
  <div>
    <el-pagination
      v-model:current-page="infor.pageindex"
      v-model:page-size="infor.pagesize"
      :page-sizes="[5, 10, 15, 20]"
      :size="size"
      :disabled="disabled"
      :background="background"
      layout="total, sizes, prev, pager, next, jumper"
      :total="infor.listcount"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
</template>

<script lang="ts" setup>
import axios from 'axios';
import { ElMessage,ElMessageBox, type ComponentSize} from 'element-plus'
import {ref,reactive,onMounted} from 'vue'
import { useRouter,useRoute } from 'vue-router';
import * as XLSX from 'xlsx';
const size = ref<ComponentSize>('default')
const background = ref(false)
const disabled = ref(false)
const router=useRouter();
const route=useRoute();
onMounted(() => {
    GetPersonnellist();
})
//查看修改数据
const chakan=(id:number)=>{
  router.push({
    path:"/PersonnelUpdate",
    query:{
      id:id
    }
  })
}
// 计算年份差（不满一年按一年算）
const calculateYearsDiff = (row:any) => {
    const currentDate = new Date();
    const entryDate = new Date(row);
    // 计算两个日期之间的年份差
    const yearDiff = currentDate.getFullYear() - entryDate.getFullYear();
    const monthDiff = currentDate.getMonth() - entryDate.getMonth();

    // 如果入职日期的月份比当前日期晚，年份差减1
    if (monthDiff < 0 || (monthDiff === 0 && currentDate.getDate() < entryDate.getDate())) {
        return Math.max(yearDiff, 1);  // 不满一年按一年算
    }

    return yearDiff || 1;  // 如果差不满一年，返回1
}
//获取已勾选的人员信息
const multipleSelection=ref([]);
const handleSelectionChange = (val: any) => {
  multipleSelection.value = val
}
///批量删除
const DeletePersonnel=()=>{
  console.log(multipleSelection.value)
  let dd=[];
  dd=multipleSelection.value.map((x:any)=>x.id)
  console.log(dd);
  axios.post("empwrite/api/Employee/DeleteEmployee",{id:dd}
  )
  .then(res=>{
    if(res.data.data>0){
      ElMessage.success("删除成功")
      GetPersonnellist();
    }
    else{
      ElMessage.error("删除失败")
    }
  })
}
///单个删除
const shanchu=(id:number)=>{
    ElMessageBox.confirm(
    '你确认要删除吗?',
    'Warning',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      axios({
        method:"post",
        url:"empwrite/api/Employee/DeleteEmployeeById",
        params:{
          id:id
        }
      })
  .then(res=>{
    if(res.data.data>0){
      ElMessage.success("删除成功")
      GetPersonnellist();
    }
    else{
      ElMessage.error("删除失败")
    }
  })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })

}
const tableData = ref([]);
const infor=ref({
    employeeName:"",
    phone:"",
    departmentId:"",
    postsId:"",
    employeeCategory:"",
    pageindex:1,
    pagesize:5,
    pagelist:0,
    listcount:0
})
//部门
const Department = ref([
    { label: 'CEO', value: 1 },
    { label: '财务部', value: 2 },
    { label: '运营部', value: 3 },
    { label: '人事部', value: 4 },
    { label: '策划部', value: 5 },
])
//职位
const Positions = ref([
    { label: '董事长', value: 1},
    { label: '财务部长', value: 2},
    { label: '运营部长', value: 3},
    { label: '人事部长', value: 4},
    { label: '策划部长', value: 5},
])
const Position:any=ref([]);
const bumen=(id:number)=>{
  Position.value = Positions.value.filter(positions => positions.value == id);
  const selectedPosition = Department.value.find(position => position.value === id);
    if (selectedPosition) {
      infor.value.departmentId = selectedPosition.label;
    }
}
//获取职位信息
const zhiwei=(id:number)=>{
  const selectedPosition = Positions.value.find(position => position.value === id);
    if (selectedPosition) {
        infor.value.postsId = selectedPosition.label;
    }
}
//获取人员信息
const GetPersonnellist=()=>{
  console.log(infor)
    axios({
        method:"get",
        url:"empread/api/Employee/GetEmployees",
        params:{
            employeeName:infor.value.employeeName,
            phone:infor.value.phone,
            departmentId:infor.value.departmentId,
            postsId:infor.value.postsId,
            employeeCategory:infor.value.employeeCategory,
            pageindex:infor.value.pageindex,
            pagesize:infor.value.pagesize,
        }
    })
    .then(res=>{
        tableData.value=res.data.data.plist
        infor.value.pagelist=res.data.data.pagecount
        infor.value.listcount=res.data.data.plistcount
        console.log(infor.value.pageindex)
        console.log(infor.value.pagesize)
    })
}
//重置
const resetForm = () => {
    infor.value.employeeName=""
    infor.value.phone=""
    infor.value.departmentId=""
    infor.value.postsId=""
    infor.value.employeeCategory=""
}
//跳转新增
const JumptoNew=()=>{
    router.push("/PersonnelAdd")
}
//分页
const handleSizeChange = (val: number) => {
  infor.value.pagesize=val;
  GetPersonnellist();
}
const handleCurrentChange = (val: number) => {
  infor.value.pageindex= val;
  GetPersonnellist()
}
//导出
const exportExcel = () => {
    const worksheet = XLSX.utils.json_to_sheet(multipleSelection.value);
    const workbook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');
    const excelBuffer = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
    const blob = new Blob([excelBuffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
    const fileName = '人员登记导出数据.xlsx';
    const link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = fileName;
    link.click();
    URL.revokeObjectURL(link.href);
};
</script>
